/*
 * @Author: txy
 *  表单公式组件
 * @Date: 2019-1-30 10:46:00 
 * @Last Modified by: txy
 * @Last Modified time: 2019-10-31 14:58:46
 */

// 属性
layui.define(['zlContext', 'layer', 'zlConfig', 'form'],
    function (exports) {
        var $ = layui.$
            , zlContext = layui.zlContext
            , zlConfig = layui.zlConfig
            , zlConfig = layui.zlConfig
            , statusName = zlConfig.global.result.statusName
            , msgName = zlConfig.global.result.msgName
            , OK = zlConfig.global.result.okState
            , dataName = zlConfig.global.result.dataName
            , ERROR = zlConfig.global.result.errorState
            , form = layui.form
            , layer = layui.layer
            , formulacmp = {};
        // 时间戳
        var generalWidgetId = function () {
            var oDate = new Date(); //实例一个时间对象；
            var id = oDate.getFullYear() +
                (oDate.getMonth() + 1) +
                oDate.getDate() +
                oDate.getHours() +
                oDate.getMinutes() +
                oDate.getSeconds() +
                oDate.getMilliseconds();
            return id;
        }
        //公式类型集合
        var gongsArr
        //组件重画消息处理
        layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
            if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('zlformulacmp') >= 0) {
                var elemVal = $(WParam.elem).attr('value') != "" ? $(WParam.elem).attr('value').replace(/'/g, '"') : '';
                formulacmp.render($(WParam.elem), elemVal);
            }
        });


        /**
         * @param {*} $elem  目标元素值
         * @param {*} value 获取已经设置的公式
         * @param {*} settings  自定义配置项  需是对象
         * @param {*} callback 各回调函数 需要是对象
         */
        var callback = {};
        formulacmp = {
            render: function ($elem, value, settings, callback) {
                if (callback == undefined) {
                    callback = $elem.attr("callback");
                }
                formulacmp.$parentelem = $elem;
                if ($elem.attr('loaded')) {
                    return;
                }
                if ($($elem).is('[settings]')) {
                    settings = $($elem).attr('settings');
                }
                var attrTypesList = [
                    { name: '请选择条件', field: '' },
                    { name: '字体大小', field: 'font-size' },
                    { name: '字体颜色', field: 'color' },
                    { name: '背景', field: 'background' },
                    { name: '高', field: 'height' },
                    { name: '行高', field: 'line-height' },
                    { name: '显示隐藏', field: 'display' }
                ];
                var parameterList = [
                    { name: '当前用户的ID', field: 'cxt.getUserId()' },
                    { name: '当前登录用户', field: 'cxt.getUser()' },
                    { name: '当前登录用户机构ID', field: 'cxt.getUserOrgId()' },
                    { name: '当前登录用户角色ID', field: 'cxt.getUserRoleId()' },
                    { name: '当前登录用户部门ID', field: 'cxt.getUserDeptId()' },
                    { name: '当前登录用户code', field: 'cxt.getUserCode()' },
                    { name: '当前登录用户机构code', field: 'cxt.getUserOrgCode()' },
                    { name: '当前登录用户角色code', field: 'cxt.getUserRoleCode()' }
                ];
                var symbolTypeList = [
                    { name: '请选择条件', field: '' },
                    { name: '等于', field: '==' },
                    { name: '不等于', field: '!=' },
                    { name: '大于', field: '>' },
                    { name: '大于或等于', field: '>=' },
                    { name: '小于', field: '<' },
                    { name: '小于或等于', field: '<=' }
                ]
                var options = (settings ? eval('(' + settings + ')') : {})
                    , dataurl = options.dataurl
                    , datas = eval('(' + options.sourcedata + ')') || []
                    , defaultOptions = {
                        attrTypes: attrTypesList
                        , method: 'get'
                        , params: '{}'
                        , dataurl: ""
                        , value: ""
                        , symbolType: symbolTypeList
                        , parameter: parameterList
                        , isordinary: true // 是否启用普通公式
                        , placeholder: '请填写或者配置公式'
                        , isInputType: false // 是否开启input形式的公式
                        , tbid: ''
                        , queryurl: ''
                        , setmode: 'groovy'  // 输入语言类

                    };

                options = $.extend({}, defaultOptions, options);
                if ($elem.length != 1) {
                    layui.error("重复或不存在的组件名称[" + $elem.attr("name") + "]");
                    return;
                }
                options.value = ((value === undefined || value === null || value === "") ? ($elem.attr("value")!= undefined ? $elem.attr("value").replace(/'/g, '"') : '') : value);
                //formulacmp.init($elem, value, options, datas, callback);
                if (options.value != ''  && $elem.attr('loaded') == "1" && isInputType==true) {
                    if(isInputType==true && (options.value !== $elem.val())){
                        $elem.val((options.value ? options.value.replace(/\"/g, "\'") : ''));
                    }
                } else {
                    formulacmp.init($elem, value, options, datas, callback);
                }
                if (options.isInputType == true) {
                    $elem.attr('loaded', 1);
                }
            },
            init: function ($elem, value, options, datas, callback) {
                var cmpName = $elem.attr('name');
                var showDown, customPopShow, generalConditionsFun, splicingConditionHtml, customPopFun, editor,
                    customBtnName = "custom-btn-" + cmpName,
                    cmpNameBtn = cmpName + '-btn',
                    delspanid = cmpName + '-delspan';
                // formulaspanid = cmpName + '-formulaspan';
                options['name'] = cmpName;
                if (options.isInputType == true) {
                    // lay-verify="required"
                    var getVal = '';
                    if (value && value != "" && formulacmp.isJSON(value)) {
                        var valueObj = eval('('+value+')');
                        getVal = valueObj.formulaName;
                    }else{
                        getVal = value;
                    }
                    var html = [
                        , '<input type="text" name="' + cmpName + '" lay-filter="' + cmpName + '-filter" class="layui-input" placeholder="' + (options.placeholder) + '" value="' + getVal + '" style="padding-right:60px;" autocomplete="off">'
                        , '<i class="layui-icon layui-icon-close layui-i-del" id="' + delspanid + '" style="position:absolute; right: 30px; top:11px; z-index:2;"></i>'
                        , '<i class="zlui-icon zlui-icon-gongs" id="' + cmpNameBtn + '" style="    position: absolute;right: 5px;top: 9px;z-index: 2;font-size: 20px; "></i>'
                    ];
                    $elem.append(html.join(''));
                }
                var $input = $elem.find('input[name="' + cmpName + '"]');
                $('#' + delspanid).hide();
                $input.on('mouseenter', function () {
                    if ($(this).val() != "") {
                        $('#' + delspanid).show();
                    }
                });
                $input.on('mouseleave', function () {
                    $('#' + delspanid).hide();
                });
                $('#' + delspanid).on('mouseenter', function () {
                    $('#' + delspanid).show();
                });
                $('#' + delspanid).on('mouseleave', function () {
                    $('#' + delspanid).hide();
                });
                var optionStr = [];
                // 获取操作的属性
                var optionObj = options.attrTypes
                for (var i = 0; i < optionObj.length; i++) {
                    optionStr.push('<option value="' + optionObj[i].field + '">' + optionObj[i].name + '</option>')
                }
                // 获取操作符类型
                var optionSymbol = options.symbolType;
                var optionSymbolStr = [];
                for (var n = 0; n < optionSymbol.length; n++) {
                    optionSymbolStr.push('<option value="' + optionSymbol[n].field + '">' + optionSymbol[n].name + '</option>')
                }
                // 获取参数名
                var parameter = options.parameter
                var parameterStr = [];
                for (var b = 0; b < parameter.length; b++) {
                    parameterStr.push('<option value="' + parameter[b].field + '">' + parameter[b].name + '</option>')
                }
                // 点击弹出公式弹框
                showDown = function (customBtnName, options) {
                    var isSuccess = false;
                    // 异步请求回来的公式类型
                    if (options.dataurl != '') {
                        $.ajax({
                            type: options.method
                            , async: false
                            , url: options.dataurl
                            , data: eval('(' + options.params + ')')
                            , dataType: 'json'
                            , async: false
                            , success: function (res) {
                                if (res[statusName] == OK) {
                                    datas = res[dataName];
                                    isSuccess = true;
                                    return datas;
                                } else {
                                    throw Error(res[msgName]);
                                }
                            }
                            , error: function (e, m) {
                                throw Error(m);
                            }
                        });
                    }
                    if (!isSuccess) { return; }
                    var heightNum = "560";
                    if (options.isordinary == true) {
                        heightNum = "450";
                    }
                    var addformulaPop = layer.open({
                        type: 1
                        , id: 'formulaInterface'
                        , title: options.isordinary == true ? "公式" : "公式定义"
                        , area: ['900px', heightNum+'px']
                        , content: options.isordinary == true ? formulacmp.addformulaHtml(customBtnName, options) : formulacmp.customFormulaHtml(datas, options)
                        , btn: ['确定', '取消']
                        , success: function () {
                            if (options.isordinary) {
                                if (value && value != "" && formulacmp.isJSON(value)){
                                    // 如果value值是对象，就查询公式
                                    var getValue = eval('('+value+')');
                                    if (getValue.hasOwnProperty('rwid')) {
                                        var obj = { RWID: getValue.rwid };
                                        zlContext.headerAjax(layui.cache['contentPath'] + '/manager/coremodelevent/query', 'post', JSON.stringify(obj), function (results) {
                                            if (results[statusName] == OK) {
                                                // 重置value的值，根据公式查询回来
                                                var newValue = eval('('+results.obj[0].MODELE_VALUE+')');
                                                zlContext.autoFill($('.select-type-form'), newValue);
                                                // 如果是复杂公式，对应的简单公式的内容要隐藏
                                                // return value 
                                                $("."+customBtnName).attr('value',JSON.stringify(newValue).replace(/\"/g, '\''));
                                            } else {
                                                zlContext.errorMsg(results[msgName]);
                                            }
                                        });
                                    }
                                }else{
                                    // 非input公式组件
                                    if(value && value != "" && !options.isInputType){
                                        zlContext.autoFill($('.select-type-form'), value);
                                    }else{
                                        // form.val("selectform", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                                        //     "formulaText": value // "name": "value"
                                        // });
                                    }
                                }
                                form.render();
                                // 点击跳出自定义公式界面
                                $("." + customBtnName).off('click');
                                $("body").on('click', "." + customBtnName, function () {
                                    var attrVal = $(this).attr('value').replace(/'/g, '"');
                                    attrVal = attrVal.replace(/thtip/g, '\'');
                                    customPopShow(datas,attrVal);
                                });
                            } else {
                                customPopFun(value);
                            }
                        }
                        , yes: function (index) {
                            // 添加校验
                            formulacmp.validateForm(value, callback, options, addformulaPop,$input);
                        }
                        , end: function (index) {
                            // value = $elem.attr("value").replace(/'/g, '"');
                        }
                    });
                }
                // 点击自定义按钮弹出自定义弹框
                customPopShow = function (datas,getvalue) {
                    layer.open({
                        type: 1
                        , id: 'customformulaInterface'
                        , title: "公式定义"
                        , area: ['900px', '560px']
                        , content: formulacmp.customFormulaHtml(datas, options)
                        , btn: ['确定', '取消']
                        , success: function () {
                            if (options.isordinary == true && getvalue && getvalue != "" && !formulacmp.isJSON(getvalue)) {
                                if(options.isInputType == true){
                                    customPopFun();
                                }else{
                                    customPopFun(getvalue);
                                }
                            }else{
                                customPopFun(getvalue);
                            }
                            
                        }
                        , yes: function (index) {
                            var formulaVal = editor.getValue();
                            $(".formulaCmp-textarea").val(formulaVal);
                            layer.close(index);
                        }
                    });
                }

                // 公式定义弹出框事件
                customPopFun = function (value) {
                    var modeLag = "ace/mode/" + options.setmode;
                    var selectType, gongsxqStr;
                    // 高亮编辑区
                    ace.require("ace/ext/language_tools");
                    editor = ace.edit("formula-text");
                    editor.setOptions({
                        enableBasicAutocompletion: true,
                        enableSnippets: true,
                        enableLiveAutocompletion: true,//只能补全
                    });
                    editor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示
                    editor.getSession().setMode(modeLag);//语言
                    editor.setFontSize(14);
                    editor.on("change", function (e) {
                        editor.execCommand("startAutocomplete");
                    })
                    if(value != undefined){
                        if (value && value != "" && formulacmp.isJSON(value)){
                            var getValue = eval('('+value+')');
                            if ((getValue.formulaCmpType != "ordinary" && getValue.hasOwnProperty('formulaText')) || (!options.isordinary && getValue.hasOwnProperty('formulaText'))) {
                                editor.setValue(getValue.formulaText)
                            }
                        }else{
                            if(value && value != "" && !options.isInputType && formulacmp.isJSON(value)){
                                var getValue = eval('('+value+')');
                                if (getValue.constructor === Object) {
                                    editor.setValue(getValue.formulaText);
                                }else{
                                    editor.setValue(value);
                                }
                                
                            }else{
                                editor.setValue(value);
                            }
                        }
                    }
                    
                    // 公式的显示隐藏事件
                    $("#function-type").find("li").first().addClass('active');
                    selectType = $("#function-type li.active").attr("data-type");
                    $("#function-name").find('li[data-type="' + selectType + '"]').show();
                    $("#function-name").find('li[data-type="' + selectType + '"]').first().addClass('active');
                    gongsxqStr = $("#function-name li.active").attr("data-shuom");
                    $("#formula-explanation").text(gongsxqStr);
                    // 点击公式类型切换公式名的内容
                    $("#function-type").find("li").click(function () {
                        $(this).addClass('active').siblings().removeClass('active');
                        selectType = $(this).attr("data-type");
                        $("#function-name").find('li').hide().removeClass('active');
                        $("#function-name").find('li[data-type="' + selectType + '"]').show();
                        $("#function-name").find('li[data-type="' + selectType + '"]').first().addClass('active');
                        gongsxqStr = $("#function-name li.active").attr("data-shuom");
                        $("#formula-explanation").text(gongsxqStr);
                    });
                    // 单击公式名样式和公式说明切换
                    $("#function-name").find("li").click(function () {
                        $(this).addClass('active').siblings().removeClass('active');
                        gongsxqStr = $("#function-name li.active").attr("data-shuom");
                        $("#formula-explanation").text(gongsxqStr);
                    });
                    // 双击公式名直接把公式放置到文本框里面
                    $("#function-name li").dblclick(function () {
                        var gongsStr = $(this).text();
                        editor.insert(gongsStr);
                    });

                    //双击变量名直接把公式放置到文本框里面
                    $("#variable-list li").click(function () {
                        $(this).addClass('active').siblings().removeClass('active');
                    });
                    $("#variable-list li").dblclick(function () {
                        var gongsStr = $(this).find('span').text();
                        editor.insert(gongsStr);
                    });

                    // 点击搜索事件
                    $("#formla-search-btn").click(function () {
                        searchFun();
                    });

                    // 搜索框回车事件
                    $('#formla-search').keydown(function (e) {
                        if (e.keyCode == 13) {
                            searchFun();
                        }
                    });
                    // 搜索框里面搜索出来的公式
                    $("body").on('dblclick', ".search-result li", function () {
                        var gongsStr = $(this).text();
                        editor.insert(gongsStr);
                    })
                }

                // 搜索函数
                var searchFun = function () {
                    var searchStr = $("#formla-search").val();
                    var formlaTypeArr = [], gongsmcStr = [];
                    $(".search-result").empty();
                    $("#function-type li").each(function () {
                        if ($(this).text().indexOf(searchStr) > -1) {
                            formlaTypeArr.push($(this).attr('data-type'));
                        }
                    });
                    if (formlaTypeArr && formlaTypeArr.length > 0) {
                        for (var d = 0; d < gongsArr.length; d++) {
                            if (formlaTypeArr.indexOf(gongsArr[d].gongslx) > -1) {
                                for (var k = 0; k < gongsArr[d].gongsm.length; k++) {
                                    var gongsmc = gongsArr[d].gongsm[k];
                                    gongsmcStr.push('<li data-shuom=' + gongsmc.explain + ' data-name="' + gongsmc.name + '" data-type="' + gongsArr[d].gongslx + '">' + gongsmc.val + '</li>');
                                }
                            }
                        }
                    }
                    $("#function-name li").each(function () {
                        var t = $(this);
                        if ($(this).text().indexOf(searchStr) > -1) {
                            gongsmcStr.push('<li data-shuom="' + t.attr("data-shuom") + '" data-name="' + t.attr("data-name") + '" data-type="' + t.attr("data-type") + '">' + t.text() + '</li>');
                        }
                    });
                    $(".search-result").append(gongsmcStr.join(''));
                }
                //出现弹出框,如果是按钮形式就直接弹出，否则点击后才能弹出
                var setValue = function (val) {
                    if(val != 'null' ){
                        var flag = formulacmp.isJSON(val);
                        if (flag == true && val != "") {
                            val = eval('('+val+')');
                            $input.val(val.formulaName);
                        } else {
                            $input.val(val);
                        }
                    }
                    
                };
                if (options.isInputType == true) {
                    $('#' + cmpNameBtn).on('click', function () {
                        showDown(customBtnName, options);
                    });
                    //初始化
                    setValue(options.value ? options.value : '');
                } else {
                    showDown(customBtnName, options);
                }

                // 删除公式回调函数
                $('#' + delspanid).on('click', function () {
                    $input.val('');
                    // input形式回调
                    var parentObj = $(this).parent();
                    var parentName = parentObj.attr("name");
                    //$input.val("");
                    var param = { interest: parentName, operation: "del" }
                    formulacmp.$parentelem.trigger("afterselect", param);
                });

            },

            /**
            * 设置光标位置
            * @param ctrl  需要设置对象
            * @param pos 对象中内容的光标的所在位置小标从0开始
            */
            setCaretPosition: function (element, pos) {
                if (element.setSelectionRange) {
                    element.focus();
                    element.setSelectionRange(pos, pos);
                } else if (element.createTextRange) {
                    var range = element.createTextRange();
                    range.collapse(true);
                    range.moveEnd('character', pos);
                    range.moveStart('character', pos);
                    range.select();
                }
            },

            /**
            * 在光标后面插入文本
            * @param textDom  需要设置对象
            * @param value 插入的文本
            */
            insertAfterText: function (textDom, value) {
                var selectRange;
                if (document.selection) {
                    // IE Support
                    textDom.focus();
                    selectRange = document.selection.createRange();
                    selectRange.text = value;
                    textDom.focus();
                } else if (textDom.selectionStart || textDom.selectionStart == '0') {
                    // Firefox support
                    var startPos = textDom.selectionStart;
                    var endPos = textDom.selectionEnd;
                    var scrollTop = textDom.scrollTop;
                    textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length);
                    textDom.focus();
                    textDom.selectionStart = startPos + value.length;
                    textDom.selectionEnd = startPos + value.length;
                    textDom.scrollTop = scrollTop;
                }
                else {
                    // textDom.getValue+=value;
                    textDom.value = textDom.getValue() + value
                    // textDom.value += value;
                    textDom.focus();
                }
            },


            /**
            * 校验表单
            * @param customBtnName 设置自定按钮id
            * @param options 设置的属性 是个对象
            */
            validateForm: function (value, callback, options, addformulaPop,$input) {
                var formulaName,param={},conditionsObj = {};
                if (options.value == "") {
                    formulaName = "formula" + generalWidgetId();
                } else {
                    if (formulacmp.isJSON(options.value)) {
                        var oldValue = eval('('+options.value.replace(/'/g, '"')+')');
                        formulaName = oldValue.formulaName;
                    } else {
                        formulaName = "formula" + generalWidgetId();
                    }
                }
                if (options.isordinary == true) {
                    var conditionsArr = [];
                    form.on('submit(formula-submit-btn)', function (data) {
                        var formField = data.field;
                        conditionsObj = { interest: formField.interest, conditionType: formField.conditionType, implementType: formField.implementType, formulaCmpType: formField.formulaCmpType, formulaAttrVal: formField.formulaAttrVal };
                        conditionsObj['formulaText'] = formField.formulaText;
                        param = { MODELE_NAME: formulaName, MODELE_VALUE: conditionsObj, MODELE_TYPE: formField.implementType, value: value,addformulaPop:addformulaPop};
                        if (options.isInputType) {
                            // input形式回调
                            formulacmp.$parentelem.trigger("afterselect", param);
                        } else {
                            callback.callbackFormula(param)
                        }
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                    $("#formula-submit-btn").trigger("click");
                    
                } else {
                    ace.require("ace/ext/language_tools");
                    var editor = ace.edit("formula-text");
                    var editorVal = editor.getValue();
                    // conditionsObj['formulaText'] = editorVal;
                    param = { MODELE_NAME: formulaName, MODELE_VALUE: editorVal,  value: value, addformulaPop:addformulaPop};
                    if (options.isInputType) {
                        // input形式回调
                        formulacmp.$parentelem.trigger("afterselect", param);
                        $input.val(editorVal);
                        if(options.isordinary==false){
                            layer.close(addformulaPop);
                        }
                    } else {
                        callback.callbackFormula(param);
                    }
                }
                
            },

            /**
            * 公式界面
            * @param customBtnName 设置自定按钮id
            * @param options 设置的属性 是个对象
            */
            addformulaHtml: function (customBtnName, options) {
                var optionStr = [];
                // 获取操作的属性
                var optionObj = options.attrTypes
                for (var i = 0; i < optionObj.length; i++) {
                    optionStr.push('<option value="' + optionObj[i].field + '">' + optionObj[i].name + '</option>')
                }
                // 获取操作符类型
                var optionSymbol = options.symbolType;
                var optionSymbolStr = [];
                for (var n = 0; n < optionSymbol.length; n++) {
                    optionSymbolStr.push('<option value="' + optionSymbol[n].field + '">' + optionSymbol[n].name + '</option>')
                }
                // 获取参数名
                var parameter = options.parameter
                var parameterStr = [];
                for (var b = 0; b < parameter.length; b++) {
                    parameterStr.push('<option value="' + parameter[b].field + '">' + parameter[b].name + '</option>')
                }
                var interestVal = options.hasOwnProperty('name') ? options['name'] : '';
                var placeholderStr = "示例：'"+options.placeholder+"'" || '请输入符合公式的内容';
                // lay-verify="required"
                var getVal = '';
                if(options.value.constructor === Object){
                    var getValStr =  JSON.stringify(options.value).replace(/\'/g, 'thtip');
                    getVal = getValStr.replace(/\"/g, '\'');
                }
                var moVal = (options.value ?  (options.value.constructor === Object ? getVal : options.value.replace(/\"/g, '\'')) : "")
                var htmlStr = [
                    '<div class="formulaCmp-box"><div class="select-type"><form class="layui-form select-type-form" lay-filter="selectform">'
                    , '     <div class="layui-form-item">'
                    , '         <label class="layui-form-label" style="width:100px">选择属性</label>'
                    , '         <div class="layui-input-block">'
                    , '             <input type="text" name="interest" id="interest-input" class="layui-input" placeholder="请选择属性" style="position:absolute;z-index:2;width:calc(100% - 32px); background-color: rgba(247, 244, 244, 1);"  value="' + interestVal + '" autocomplete="off" ' + (interestVal != '' ? 'disabled' : '') + '>'
                    // , '             <select id="inputSelect" type="text" name="inputSelect" lay-filter="selectType" class="layui-select" lay-search ' + (interestVal != '' ? 'disabled' : '') + '>'
                    // , optionStr.join('')
                    // , '             </select>'
                    , '         </div>'
                    , '     </div>'
                    , '     <div class="layui-form-item">'
                    , '         <ul class="add-attr"></ul>'
                    , '     </div>'
                    , '     <fieldset class="layui-elem-field layui-field-title"><legend>公式条件</legend></fieldset>'
                    , '     <div class="layui-form-item" style="margin-bottom:0px;">'
                    , '         <div class="layui-inline">'
                    , '             <label class="layui-form-label" style="width:100px">执行类型</label>'
                    , '             <div class="layui-input-inline" style="width:auto">'
                    , '                 <input type="radio" name="implementType" value="04B5397570804B428A3966E28A78D562" title="初始化公式" checked="">'
                    , '                 <input type="radio" name="implementType" value="23FB7A4D0F5B40E1844731C81908F97A" title="运行期公式">'
                    , '                 <input type="radio" name="implementType" value="371EF01B3FD5439CB6A1899C02CCC685" title="结束期公式（校验）">'
                    , '             </div>'
                    , '         </div>'
                    , '     </div>'
                    , '     <div class="layui-form-item formula-input-box">'
                    , '         <label class="layui-form-label" style="width:100px">公式=</label>'
                    , '         <div class="layui-input-block">'
                    , '             <textarea placeholder="'+placeholderStr+'" class="layui-textarea formulaCmp-textarea complex-condition" name="formulaText" style="height:200px;"></textarea><button class="layui-btn layui-btn-sm ' + customBtnName + '" type="button" style="float:right" value="'+moVal+'">自定义</button>'
                    , '         </div>'
                    , '     </div>'
                    , '     <button id="formula-submit-btn" class="layui-hide" type="button" lay-submit lay-filter="formula-submit-btn">提交</button>'
                    , '</form>'
                    , '</div></div>'
                ];
                return htmlStr.join('');
            },

            customFormulaHtml: function (datas, options) {
                if (datas.length == 0) {
                    return;
                }
                gongsArr = eval('(' + datas + ')');
                var gongslxStr = [], gongsmcStr = [], variableStr = [], tbdatas = [];
                for (var j = 0; j < gongsArr.length; j++) {
                    gongslxStr.push('<li data-type="' + gongsArr[j].gongslx + '">' + gongsArr[j].gongslxmc + '</li>');
                    for (var k = 0; k < gongsArr[j].gongsm.length; k++) {
                        var gongsmc = gongsArr[j].gongsm[k];
                        var gongssm = gongsmc.explain.replace(/\"/g, "&quot;");
                        gongsmcStr.push('<li data-shuom="' + gongssm + '" data-name="' + gongsmc.name + '" data-type="' + gongsArr[j].gongslx + '">' + gongsmc.val + '</li>');
                    }
                }
                if (options.tbid != '' && options.queryurl != '') {
                    $.ajax({
                        type: options.method
                        , async: false
                        , url: options.queryurl
                        , data: { tableid: options.tbid }
                        , dataType: 'json'
                        , async: false
                        , success: function (res) {
                            if (res[statusName] == OK) {
                                tbdatas = res[dataName];
                            } else {
                                throw Error(res[msgName]);
                            }
                        }
                        , error: function (e, m) {
                            throw Error(m);
                        }
                    });
                }
                for (var i = 0; i < tbdatas.length; i++) {
                    variableStr.push('<li><span>' + tbdatas[i].MXZD_BIANH + '</span>(' + tbdatas[i].MXZD_MINGC + ')</li>');
                }
                // <button type="button" class="layui-btn layui-btn-xs">检查合法性</button>
                var frm = [
                    '<div class="custom-formula">'
                    , '     <div class="layui-row layui-col-space8">'
                    , '         <div class="layui-col-xs9">'
                    , '             <div style="overflow: hidden;"><h5 style="float:left">请在下面的文本编辑框里面输入公式</h5><div  class="check-btn-box" style="float:right"></div></div>'
                    , '             <div id="formula-text" class="formula-text" style="height:187px;"></div>'
                    , '         </div>'
                    , '         <div class="layui-col-xs3">'
                    , '             <div class="formula-search-box">'
                    , '                 <input id="formla-search" type="text" name="search" placeholder="请输入公式类型或公式名" value="" style="font-size:13px"><button type="button" id="formla-search-btn" class="layui-btn layui-btn-xs">搜索</button>'
                    , '             </div>'
                    , '             <ul class="search-result" style="height:180px"></ul>'
                    , '         </div>'
                    , '     </div>'
                    , '     <div class="layui-row layui-col-space5">'
                    , '         <div class="layui-col-xs2"><div class=" borderClass">'
                    , '             <h5>公式类型：</h5>'
                    , '             <ul id="function-type" class="content-box">' + gongslxStr.join('') + '</ul>'
                    , '         </div></div>'
                    , '         <div class="layui-col-xs2"><div class=" borderClass">'
                    , '             <h5>公式名：</h5>'
                    , '             <ul id="function-name" class="content-box">' + gongsmcStr.join('') + '</ul>'
                    , '         </div></div>'
                    , '         <div class="layui-col-xs5"><div class=" borderClass">'
                    , '             <h5>变量：</h5>'
                    , '             <ul id="variable-list" class="content-box">' + variableStr.join('') + '</ul>'
                    , '         </div></div>'
                    , '         <div class="layui-col-xs3"><div class=" borderClass">'
                    , '             <h5>公式说明：</h5>'
                    , '             <p id="formula-explanation" class="content-box" style="padding:0 2px"></p>'
                    , '         </div></div>'
                    , '     </div>'
                    , '</div>'
                ];
                return frm.join('');
            }
            , isJSON: function (str) {
                try {
                    if (typeof JSON.parse(str) == "object") {
                        return true;
                    }
                } catch (e) {
                }
                return false;
            }

        };
        exports("zlFormulaCmp", formulacmp);
    });